import { Doughnut } from 'react-chartjs-2'
import './setup' // 确保Chart.js组件被注册
import { commonOptions, colors } from './chartConfig'

interface CompletionRateChartProps {
  completionRate: number
  totalTasks: number
  completedTasks: number
}

export default function CompletionRateChart({ 
  completionRate, 
  totalTasks, 
  completedTasks 
}: CompletionRateChartProps) {
  const pendingRate = 100 - completionRate

  const chartData = {
    labels: ['已完成', '待完成'],
    datasets: [
      {
        data: [completionRate, pendingRate],
        backgroundColor: [
          colors.success.bg,
          'rgba(148, 163, 184, 0.3)'
        ],
        borderColor: [
          colors.success.border,
          'rgba(148, 163, 184, 0.5)'
        ],
        borderWidth: 3,
        hoverOffset: 6,
        hoverBorderWidth: 4
      }
    ]
  }

  const options = {
    ...commonOptions,
    plugins: {
      ...commonOptions.plugins,
      legend: {
        display: false
      },
      tooltip: {
        ...commonOptions.plugins?.tooltip,
        callbacks: {
          label: (context: any) => {
            const label = context.label
            const value = Math.round(context.parsed)
            const count = label === '已完成' ? completedTasks : totalTasks - completedTasks
            return `${label}: ${value}% (${count} 个任务)`
          }
        }
      }
    },
    cutout: '75%',
    radius: '90%',
    animation: {
      animateRotate: true,
      duration: 1500,
      easing: 'easeOutQuart' as const
    }
  }

  return (
    <div className="h-48 relative">
      <Doughnut data={chartData} options={options} />
      {/* 中心显示完成率 */}
      <div className="absolute inset-0 flex items-center justify-center pointer-events-none">
        <div className="text-center">
          <div className="text-3xl font-bold text-theme-text mb-1">
            {completionRate}%
          </div>
          <div className="text-xs text-theme-text-muted font-medium">
            完成率
          </div>
          <div className="text-xs text-slate-400 mt-1">
            {completedTasks}/{totalTasks}
          </div>
        </div>
      </div>
      
      {/* 底部图例 */}
      <div className="mt-4 flex justify-center gap-6">
        <div className="flex items-center gap-2">
          <div className="w-3 h-3 rounded-full bg-green-500"></div>
          <span className="text-sm text-theme-text-secondary">已完成 ({completedTasks})</span>
        </div>
        <div className="flex items-center gap-2">
          <div className="w-3 h-3 rounded-full bg-slate-300"></div>
          <span className="text-sm text-theme-text-secondary">待完成 ({totalTasks - completedTasks})</span>
        </div>
      </div>
    </div>
  )
}
